package com.x.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @Author _G5niusX
 * @Date 2018/5/18 22:13
 */
public class NettyServer {
    final private int port;

    public NettyServer(int port) throws FileNotFoundException {
        this.port = port;
    }

    private FileOutputStream fileOutputStream = new FileOutputStream(new File("e://test.ico"));

    private void accept() throws InterruptedException {
        EventLoopGroup acceptEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup workEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(acceptEventLoopGroup, workEventLoopGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf byteBuf = (ByteBuf) msg;
                        int capacity = byteBuf.capacity();
                        int readableBytes = byteBuf.readableBytes();
                        byte[] bytes = new byte[readableBytes];
                        for (int i = 0; i < readableBytes; i++) {
                            bytes[i] = byteBuf.getByte(i);
                        }
                        fileOutputStream.write(bytes, 0, readableBytes);
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        cause.printStackTrace();
                        ctx.close();
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        //ctx.channel().close();
                    }
                });
            }
        });
        ChannelFuture sync = serverBootstrap.bind(port).sync();
        sync.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws InterruptedException, FileNotFoundException {
        new NettyServer(9000).accept();
        ;
    }
}
